package com.nine.demo.filemanager.file;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @Description: 本地文件操作工具类
 * @Author: 刘超
 * @Date: 2023-04-12 14:41
 */
public class FileUtil {
    public static List<String> splitFile(String fileName,int byteSize) throws IOException {
        //返回文件名List
        List<String> splitFileName = new ArrayList<>();
        File file = new File(fileName);
        int count = (int) Math.ceil(file.length() / (double) byteSize); // 拆分的文件个数
        int countLen = (count + "").length();
        //文件随机读写
        RandomAccessFile rFile = new RandomAccessFile(fileName, "r");
        long totalLen = rFile.length();

        CountDownLatch latch = new CountDownLatch(count);

        //单进程执行
        for (int i = 0; i < count; i++) {
            String partFileName = file.getPath() + "." + leftPad((i + 1) + "", countLen, '0') + ".dat";
            int readSize = byteSize;
            long startPos = (long) i * byteSize;
            long nextPos = (long) (i + 1) * byteSize;
            if (nextPos > totalLen) {
                readSize = (int) (totalLen - startPos);
            }
//            new SplitRunnable(readSize, startPos, partFileName, file, latch).run();
            splitFileName.add(partFileName);
        }



        return splitFileName;
    }

    /**
     * @Title: leftPad
     * @Description:  左填充
     * @param str
     * @param length
     * @param ch
     * @return 填充后的字符串
     * @throws
     */
    public static String leftPad(String str, int length, char ch) {
        if (str.length() >= length) {
            return str;
        }
        char[] chs = new char[length];
        Arrays.fill(chs, ch);
        char[] src = str.toCharArray();
        System.arraycopy(src, 0, chs, length - src.length, src.length);
        return new String(chs);
    }
}
